package com.lw.common.utils

import android.annotation.SuppressLint
import android.app.Activity
import android.os.Build
import android.view.WindowManager
import androidx.core.content.ContextCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import com.lw.common.R

/**
 * @description: 修改状态栏
 * @author: yuan
 * @date: 2023/3/10/0010
 */
class StatusBar(private val activity: Activity) {
    /**
     * 将状态栏设置为传入的color
     */
    fun setColor(color: Int): StatusBar {
        val view = activity.window.decorView
        activity.window.statusBarColor = ContextCompat.getColor(activity, color)
        return this
    }

    /**
     * 设置状态栏字体颜色
     */
    fun setTextColor(isLightBackground: Boolean): StatusBar {
        val insetsController =
            WindowCompat.getInsetsController(activity.window, activity.window.decorView)
        insetsController.isAppearanceLightStatusBars = !isLightBackground
        return this
    }

    /**
     * 沉浸式状态栏
     */
    @SuppressLint("ResourceType")
    fun immersionFull(): StatusBar {
        val window = activity.window
        window.statusBarColor = ContextCompat.getColor(activity, R.color.color_00000000)
        //占满全屏，activity绘制将状态栏也加入绘制范围。
        //如此即使使用BEHAVIOR_SHOW_BARS_BY_SWIPE或BEHAVIOR_SHOW_BARS_BY_TOUCH
        //也不会因为状态栏的显示而导致activity的绘制区域出现变形
        //使用刘海屏也需要这一句进行全屏处理
        WindowCompat.setDecorFitsSystemWindows(window, false)
        //隐藏状态栏和导航栏 以及交互
        WindowInsetsControllerCompat(window, window.decorView).let {
            //隐藏状态栏和导航栏
            //用于WindowInsetsCompat.Type.systemBars()隐藏两个系统栏
            //用于WindowInsetsCompat.Type.statusBars()仅隐藏状态栏
            //用于WindowInsetsCompat.Type.navigationBars()仅隐藏导航栏
            it.hide(WindowInsetsCompat.Type.systemBars())
            //交互效果
            //BEHAVIOR_SHOW_BARS_BY_SWIPE 下拉状态栏操作可能会导致activity画面变形
            //BEHAVIOR_SHOW_BARS_BY_TOUCH 未测试到与BEHAVIOR_SHOW_BARS_BY_SWIPE的明显差异
            //BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE 下拉或上拉的屏幕交互操作会显示状态栏和导航栏
            it.systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_BARS_BY_SWIPE
        }

        //允许window 的内容可以上移到刘海屏状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            val lp = window.attributes
            lp.layoutInDisplayCutoutMode =
                WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
            window.attributes = lp
        }
        return this
    }
}